package com.hq.sys.service.impl;

import com.hq.sys.eneity.Menu;
import com.hq.sys.eneity.MenuVo;
import com.hq.sys.eneity.RoleMenu;
import com.hq.sys.eneity.RoleUser;
import com.hq.sys.mapper.MenuMapper;
import com.hq.sys.mapper.RoleMenuMapper;
import com.hq.sys.mapper.RoleUserMapper;
import com.hq.sys.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @BelongsPackage: com.hq.sys.service.impl
 * @Author: jiangjunjie
 * @CreateTime: 2024-12-22  10:03
 * @Description: TODO
 * @Version: 1.8
 */
@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private RoleUserMapper roleUserMapper;
    @Override
    public List<Menu> queryMenuList() {
      return menuMapper.select(new Menu());
    }

    @Override
    public List<Menu> queryAllMenu() {
        return menuMapper.selectAll();
    }

    @Override
    public Menu queryMenuByTitle(String title) {
        return menuMapper.selectByPrimaryKey(title);
    }

    @Override
    public Menu queryMenuById(Integer id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public int addMenu(Menu menu) {
        return menuMapper.insert(menu);
    }

    @Override
    public int updateMenu(Menu menu) {
        return menuMapper.updateByPrimaryKey(menu);
    }

    @Override
    public int deleteMenu(Integer id) {
        return menuMapper.deleteByPrimaryKey(id);
    }
    @Override
    public List<Menu> queryMenuByUid(Integer userid) {
        //根据用户id查询拥有的角色->菜单
        List<RoleUser> roleUsers = roleUserMapper.select(new RoleUser().setUid(userid));
        //根据角色查询获取所有角色id
        List<Integer> roleIds = roleUsers.stream()
                .map(RoleUser::getRid)
                .collect(Collectors.toList());

        //生成菜单集合
        List<Menu> menus = new ArrayList<>();
        for (Integer roleId : roleIds) {
            List<RoleMenu> roleMenus = roleMenuMapper.select(new RoleMenu().setRid(roleId));
            List<Integer> menuIds = roleMenus.stream()
                    .map(RoleMenu::getMid)
                    .collect(Collectors.toList());
            List<Menu> menuList = menuIds.stream()
                    .map(menuMapper::selectByPrimaryKey)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            menus.addAll(menuList);
        }
        return menus;
    }
}
